package com.dykj.fireFighting.server.elasticsearch.devHis.service.impl;

import com.dykj.fireFighting.api.elasticsearch.devHis.entity.EsDevHis;
import com.dykj.fireFighting.api.elasticsearch.devHis.service.EsDevHisService;
import com.dykj.fireFighting.api.elasticsearch.devHisWater.entity.EsDevHisWater;
import com.dykj.fireFighting.api.elasticsearch.devHisZc.entity.EsDevHisZc;
import com.dykj.fireFighting.common.core.utils.DataCleaningUtil;
import com.dykj.fireFighting.common.core.utils.ZcDataCleaning;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.server.elasticsearch.devHis.repository.EsDevHisRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.data.elasticsearch.core.query.UpdateResponse;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;


/**
 * Service实现类
 * Created by macro on 2018/6/19.
 */
@Slf4j
@DubboService
public class EsDevHisServiceImpl implements EsDevHisService {
    private static final Logger LOGGER = LoggerFactory.getLogger(EsDevHisServiceImpl.class);
    @Autowired
    private EsDevHisRepository esDevHisRepository;
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public EsDevHis importAll(EsDevHis esDevHis) {
        return esDevHisRepository.save(esDevHis);
    }

    @Override
    public PageVo<EsDevHis> searchByCenterId(String id, String isRead,String beginDate,String endDate) {
        NativeSearchQuery queryBuilder = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.boolQuery()
                        .must(QueryBuilders.termQuery("centerUnitId",id))
                        .must(QueryBuilders.termQuery("isRead","0"))
                        .must(QueryBuilders.rangeQuery("ztfssj")
                                .from(beginDate)
                                .to(endDate)
                                .includeLower(true)
                                .includeUpper(true))
                        .must(QueryBuilders.wildcardQuery("bjzt","*08*")))

                .withSort(SortBuilders.fieldSort("ztfssj").order(SortOrder.DESC))
                .withPageable(PageRequest.of(0, 15))
                .build();
        Page<EsDevHis> search = esDevHisRepository.search(queryBuilder);
        PageVo<EsDevHis> page = new PageVo<>();
        page.setTotalCount((int) search.getTotalElements());
        List<EsDevHis> paggList = new ArrayList<>();
        for (EsDevHis e : search.getContent()) {
            e.setBjztSm(DataCleaningUtil.dataCleaning(e.getBjztSm()));
            paggList.add(e);
        }
        page.setList(paggList);
        return page;
    }

    @Override
    public PageVo<EsDevHis> search(String keyword, String deviceName, Integer pageNum, Integer pageSize,String beginDate,String endDate) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //分页
        nativeSearchQueryBuilder.withPageable(pageable);
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.termQuery("unitId", keyword));
        if (StringUtils.isNotBlank(deviceName)) {
            boolQuery.must(QueryBuilders.wildcardQuery("deviceName", "*" + deviceName + "*"));
        }
        /*List<String> list=new ArrayList<>();
        list.add("1");
        list.add("2");*/
        boolQuery.mustNot(QueryBuilders.termQuery("lx","3"));
        nativeSearchQueryBuilder.withQuery(boolQuery);
        if (StringUtils.isNotBlank(beginDate) && StringUtils.isNotBlank(endDate)) {
            boolQuery.must(QueryBuilders.rangeQuery("ztfssj")
                    .from(beginDate)
                    .to(endDate)
                    .includeLower(true)     // 包含上界
                    .includeUpper(true));      // 包含下届
        }
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("ztfssj").order(SortOrder.DESC));
        //nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
        NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();

        LOGGER.info("DSL:{}", searchQuery.getQuery().toString());
        Page<EsDevHis> search = esDevHisRepository.search(searchQuery);
        PageVo<EsDevHis> page = new PageVo<>();
        page.setTotalCount((int) search.getTotalElements());
        List<EsDevHis> paggList = new ArrayList<>();
        for (EsDevHis e : search.getContent()) {
            e.setBjztSm(DataCleaningUtil.dataCleaning(e.getBjztSm()));
            paggList.add(e);
        }
        page.setList(paggList);
        return page;
    }

    @Override
    public PageVo<EsDevHis> searchGz(String keyword, String isRead, Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //分页
        nativeSearchQueryBuilder.withPageable(pageable);
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.termQuery("isRead", isRead));
        boolQuery.must(QueryBuilders.wildcardQuery("bjzt", "*07*"));
        boolQuery.must(QueryBuilders.termQuery("unitId", keyword));
        nativeSearchQueryBuilder.withQuery(boolQuery);
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("ztfssj").order(SortOrder.DESC));
        //nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
        NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
        LOGGER.info("DSL:{}", searchQuery.getQuery().toString());
        Page<EsDevHis> search = esDevHisRepository.search(searchQuery);
        PageVo<EsDevHis> page = new PageVo<>();
        page.setTotalCount((int) search.getTotalElements());
        List<EsDevHis> paggList = new ArrayList<>();
        for (EsDevHis e : search.getContent()) {
            e.setBjztSm(DataCleaningUtil.dataCleaning(e.getBjztSm()));
            paggList.add(e);
        }
        page.setList(paggList);
        return page;
    }

    @Override
    public PageVo<EsDevHis> searchOther(String keyword, Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //分页
        nativeSearchQueryBuilder.withPageable(pageable);
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.mustNot(QueryBuilders.wildcardQuery("bjzt", "*07*"));
        boolQuery.mustNot(QueryBuilders.wildcardQuery("bjzt", "*08*"));
        boolQuery.must(QueryBuilders.termQuery("unitId", keyword));
        nativeSearchQueryBuilder.withQuery(boolQuery);
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("ztfssj").order(SortOrder.DESC));
        //nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
        NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
        LOGGER.info("DSL:{}", searchQuery.getQuery().toString());
        Page<EsDevHis> search = esDevHisRepository.search(searchQuery);
        PageVo<EsDevHis> page = new PageVo<>();
        page.setTotalCount((int) search.getTotalElements());
        List<EsDevHis> paggList = new ArrayList<>();
        for (EsDevHis e : search.getContent()) {
            e.setBjztSm(DataCleaningUtil.dataCleaning(e.getBjztSm()));
            paggList.add(e);
        }
        page.setList(paggList);
        return page;
    }

    @Override
    public PageVo<EsDevHis> wbSearchGz(List<String> unitId, String isRead, Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //分页
        nativeSearchQueryBuilder.withPageable(pageable);
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.termQuery("wbRead", isRead));
        boolQuery.must(QueryBuilders.wildcardQuery("bjzt", "*07*"));
        for (String s : unitId) {
            boolQuery.should(QueryBuilders.termQuery("unitId", s));
        }
        nativeSearchQueryBuilder.withQuery(boolQuery);
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("ztfssj").order(SortOrder.DESC));
        //nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
        NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
        LOGGER.info("DSL:{}", searchQuery.getQuery().toString());
        Page<EsDevHis> search = esDevHisRepository.search(searchQuery);
        PageVo<EsDevHis> page = new PageVo<>();
        page.setTotalCount((int) search.getTotalElements());
        List<EsDevHis> paggList = new ArrayList<>();
        for (EsDevHis e : search.getContent()) {
            e.setBjztSm(DataCleaningUtil.dataCleaning(e.getBjztSm()));
            paggList.add(e);
        }
        page.setList(paggList);
        return page;
    }

    @Override
    public PageVo<EsDevHis> queryList(String sj, String bjzt, String status, String devCode, String unitId,
                                      Integer pageNum, Integer pageSize,String devName,String devType,String lx) {

        Pageable pageable = PageRequest.of(pageNum, pageSize);
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();

        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.termQuery("unitId", unitId));
        if (StringUtils.isNotBlank(bjzt)) {
            boolQuery.must(QueryBuilders.wildcardQuery("bjzt", "*" + bjzt + "*"));
        }
        if (StringUtils.isNotBlank(status)) {
            boolQuery.must(QueryBuilders.termQuery("status", status));
        }
        if (StringUtils.isNotBlank(devCode)) {
            boolQuery.must(QueryBuilders.fuzzyQuery("devCode", devCode));
        }
        if (StringUtils.isNotBlank(sj)) {
            boolQuery.must(QueryBuilders.rangeQuery("upTime")
                    .from(sj.split(",")[0])
                    .to(sj.split(",")[1])
                    .includeLower(true)     // 包含上界
                    .includeUpper(true));      // 包含下届
        }
        if (StringUtils.isNotBlank(devType)) {
            boolQuery.must(QueryBuilders.termQuery("devType", devType));
        }
        if (StringUtils.isNotBlank(lx)) {
            boolQuery.must(QueryBuilders.termQuery("lx", lx));
        }
        if (StringUtils.isNotBlank(devName)) {
            boolQuery.must(QueryBuilders.wildcardQuery("devName", "*" + devName + "*"));
        }
        nativeSearchQueryBuilder.withQuery(boolQuery);
        //分页
        nativeSearchQueryBuilder.withPageable(pageable);
        if("1".equals(status)){
            nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("fuheTime").order(SortOrder.DESC));
        }else{

            nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("ztfssj").order(SortOrder.DESC));
        }

        //nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
        NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
        log.info("实时报警DSL:{}", searchQuery.getQuery());
        Page<EsDevHis> search = esDevHisRepository.search(searchQuery);
        PageVo<EsDevHis> page = new PageVo<>();
        page.setTotalCount((int) search.getTotalElements());
        List<EsDevHis> paggList = new ArrayList<>();
        for (EsDevHis e : search.getContent()) {
            e.setBjztSm(DataCleaningUtil.dataCleaning(e.getBjztSm()));
            paggList.add(e);
        }
        page.setList(paggList);
        return page;
    }

    @Override
    public PageVo<EsDevHis> wbSearchOther(List<String> unitId, Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);

        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //分页
        nativeSearchQueryBuilder.withPageable(pageable);
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.mustNot(QueryBuilders.wildcardQuery("bjzt", "*07*"));
        boolQuery.mustNot(QueryBuilders.wildcardQuery("bjzt", "*08*"));
        for (String s : unitId) {
            boolQuery.should(QueryBuilders.termQuery("unitId", s));
        }
        nativeSearchQueryBuilder.withQuery(boolQuery);
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("ztfssj").order(SortOrder.DESC));
        //nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
        NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
        LOGGER.info("DSL:{}", searchQuery.getQuery().toString());



        Page<EsDevHis> search = esDevHisRepository.search(searchQuery);
        PageVo<EsDevHis> page = new PageVo<>();
        page.setTotalCount((int) search.getTotalElements());
        List<EsDevHis> paggList = new ArrayList<>();
        for (EsDevHis e : search.getContent()) {
            e.setBjztSm(DataCleaningUtil.dataCleaning(e.getBjztSm()));
            paggList.add(e);
        }
        page.setList(paggList);
        return page;
    }

    @Override
    public PageVo<EsDevHis> centerSearch(String keyword, String unitId, String deviceName, Integer pageNum, Integer pageSize,String beginDate,String endDate,String lx) {

        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //分页
        nativeSearchQueryBuilder.withPageable(pageable);
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.termQuery("centerUnitId", keyword));
        if (StringUtils.isNotBlank(unitId)) {
            boolQuery.must(QueryBuilders.termQuery("unitId", unitId));
        }
        if (StringUtils.isNotBlank(deviceName)) {
            boolQuery.must(QueryBuilders.wildcardQuery("deviceName", "*" + deviceName + "*"));
        }
     /*   if ("3".equals(lx)) {
            boolQuery.must(QueryBuilders.termQuery("lx", lx));
        }else{
            boolQuery.mustNot(QueryBuilders.termQuery("lx","3"));
        }*/
        if (StringUtils.isNotBlank(beginDate) && StringUtils.isNotBlank(endDate)) {
                boolQuery.must(QueryBuilders.rangeQuery("upTime")
                        .from(beginDate)
                        .to(endDate)
                        .includeLower(true)     // 包含上界
                        .includeUpper(true));      // 包含下届
        }

        if(StringUtils.isNotBlank(lx)){
            BoolQueryBuilder inQueryBuilder = QueryBuilders.boolQuery();
            String[] split = lx.split(",");
            for (int i = 0; split.length > i; i++) {

                inQueryBuilder.should(QueryBuilders.matchQuery("lx",split[i]));
            }
            boolQuery.must(inQueryBuilder);
        }
        nativeSearchQueryBuilder.withQuery(boolQuery);

        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("ztfssj").order(SortOrder.DESC));
        //nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
        NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
        LOGGER.info("DSL:{}", searchQuery.getQuery().toString());
        Page<EsDevHis> search = esDevHisRepository.search(searchQuery);
        PageVo<EsDevHis> page = new PageVo<>();
        page.setTotalCount((int) search.getTotalElements());
        List<EsDevHis> paggList = new ArrayList<>();
        for (EsDevHis e : search.getContent()) {
            e.setBjztSm(DataCleaningUtil.dataCleaning(e.getBjztSm()));
            paggList.add(e);
        }
        page.setList(paggList);
        return page;
    }

    @Override
    public void updateEsDevHis(EsDevHis esDevHis) {
        try{
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Document doc = Document.create();
            doc.put("isEffective", esDevHis.getIsEffective());
            doc.put("status", esDevHis.getStatus());
            doc.put("fuheTime", sdf1.parse(esDevHis.getFuheTime()));
            doc.put("fuhePersonId", esDevHis.getFuhePersonId());
            doc.put("fuhePerson", esDevHis.getFuhePerson());
            doc.put("fuheContent", esDevHis.getFuheContent());
            doc.put("importPart", esDevHis.getImportPart());
            UpdateQuery.Builder builder = UpdateQuery.builder(esDevHis.getId())
                    .withDocument(doc);
            UpdateQuery updateQuery = builder.build();
            UpdateResponse updateResponse = elasticsearchRestTemplate.update(updateQuery, IndexCoordinates.of("devhis"));
            System.out.println(updateResponse.getResult());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @Override
    public void updateEsDevHisIsRead(EsDevHis esDevHis) {
        Document doc = Document.create();
        doc.put("isRead", esDevHis.getIsRead());
        UpdateQuery.Builder builder = UpdateQuery.builder(esDevHis.getId())
                .withDocument(doc);
        UpdateQuery updateQuery = builder.build();
        UpdateResponse updateResponse = elasticsearchRestTemplate.update(updateQuery, IndexCoordinates.of("devhis"));
    }


    @Override
    public EsDevHis getByDevHisId(String id) {
        NativeSearchQuery queryBuilder = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.termQuery("id",id))
                .withSort(SortBuilders.fieldSort("ztfssj").order(SortOrder.DESC))
                .withPageable(PageRequest.of(0, 1))
                .build();
        LOGGER.info("DSL:{}", queryBuilder.getQuery().toString());
        Page<EsDevHis> search = esDevHisRepository.search(queryBuilder);
        List<EsDevHis> content = search.getContent();
        if (content.size() > 0) {
            return content.get(0);
        }
        return null;

    }

    @Override
    public void createMapping() {
        elasticsearchRestTemplate.putMapping(EsDevHis.class);
    }

    @Override
    public PageVo<EsDevHis> searchByCenterIdNew(String centerId, String unitId, String deviceName, Integer pageNum, Integer pageSize, String beginDate, String endDate) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.withPageable(pageable);
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (StringUtils.isNotBlank(centerId)) {
            boolQuery.must(QueryBuilders.termQuery("centerUnitId", centerId));
        }
        if (StringUtils.isNotBlank(unitId)) {
            boolQuery.must(QueryBuilders.termQuery("unitId", unitId));
        }
        if (StringUtils.isNotBlank(deviceName)) {
            boolQuery.must(QueryBuilders.wildcardQuery("devName", "*" + deviceName + "*"));
        }
        if (StringUtils.isNotBlank(beginDate) && StringUtils.isNotBlank(endDate)) {
            boolQuery.must(QueryBuilders.rangeQuery("upTime")
                    .from(beginDate)
                    .to(endDate)
                    .includeLower(true)     // 包含上界
                    .includeUpper(true));      // 包含下届
        }
        nativeSearchQueryBuilder.withQuery(boolQuery);
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("upTime").order(SortOrder.DESC));
        NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
        Page<EsDevHis> search = esDevHisRepository.search(searchQuery);
        PageVo<EsDevHis> page = new PageVo<>();
        page.setTotalCount((int) search.getTotalElements());
        List<EsDevHis> paggList = new ArrayList<>();
        for (EsDevHis e : search.getContent()){
            paggList.add(e);
        }
        page.setList(paggList);
        return page;
    }

}
